import React from 'react';
import { useStaticQuery, graphql, Link } from 'gatsby';
import { DocumentTitle, HeadLine } from '../../components';
import { BasicLayout } from '../../layouts';

import styles from './index.module.less';

const HomePage = () => {
  const data = useStaticQuery(graphql`
    query loadPagesQuery {
      allMarkdownRemark(
        limit: 1000
        sort: { fields: frontmatter___date, order: DESC }
      ) {
        nodes {
          id
          frontmatter {
            date(formatString: "YYYY年MM月DD日")
            path
            thumbnail
            title
          }
        }
      }
    }
  `);

  const {
    allMarkdownRemark: { nodes = [] },
  } = data;

  const Articles = React.useMemo(() => {
    return nodes.map(({ id, frontmatter = {} }) => {
      const { title, thumbnail, path, date } = frontmatter;
      return (
        <div key={id} className="article-card">
          <div className="article-card-inner">
            <Link to={path}>
              <img src={thumbnail} alt={title}></img>
            </Link>
            <div className="card-content">
              <Link to={path}>
                <h2 className="arttcle-title">{title}</h2>
              </Link>
              <p className="article-date">{date}</p>
            </div>
          </div>
        </div>
      );
    });
  }, [nodes]);

  const lastestPathUrl = React.useMemo(() => {
    if (nodes.length) {
      const firstNode = nodes[0];
      const {
        frontmatter: { path },
      } = firstNode;
      return path;
    }
    return '/';
  }, [nodes]);

  return (
    <div className={styles.homePage}>
      <BasicLayout>
        <DocumentTitle title="小二柴" />
        <HeadLine lastestPathUrl={lastestPathUrl} />
        <h2 className="post-list-title">推送列表</h2>
        <div className="article-list">{Articles}</div>
      </BasicLayout>
    </div>
  );
};

export default React.memo(HomePage);
